package com.xinyan.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.xinyan.dto.DruidDto;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author xinyan.xie
 * @description 连接池配置
 * @date 2020/5/15
 */
public class MysqlDruid {
    public static DruidDataSource dataSource;

    //2.获取连接
    public static Connection getConnection(DruidDto druidDto) {
        try {
            dataSource = new DruidDataSource();
            dataSource.setDriverClassName(druidDto.getDriverClass());
            dataSource.setUrl(druidDto.getUrl());
            dataSource.setUsername(druidDto.getUsername());
            dataSource.setPassword(druidDto.getPassword());
            //初始大小
            dataSource.setInitialSize(10);
            //最大大小
            dataSource.setMaxActive(50);
            //最小大小
            dataSource.setMinIdle(10);
            //检查时间
            dataSource.setMaxWait(5000);
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
